package br.com.fatecmococa.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class DAO {
    
    
    
    private static final SessionFactory sessionFactory = new AnnotationConfiguration()
            .configure("hibernate.cfg.xml").buildSessionFactory();
    
    private static final ThreadLocal threadLocal = new
            ThreadLocal();

    public DAO() {
    }
    
    public static Session getSession(){
        Session session = (Session)threadLocal.get();
        if(session == null){
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }
    
    public void begin(){
        getSession().beginTransaction();
    }
    
    public void commit(){
        getSession().beginTransaction().commit();
    }
    
    public void rollback(){
        try{
            getSession().beginTransaction().rollback();
        }catch(HibernateException e){
            e.printStackTrace();
        }
        try{
            getSession().close();
        }catch(HibernateException e){
            e.printStackTrace();
        }
        threadLocal.set(null);
    }
        
    public static void close(){
        getSession().clear();
        getSession().close();
        threadLocal.set(null);
    }
    
}
